import { AuthEnum } from '../enums/auth.enum'
import { DecoratorEnum } from '../enums/decorator.enum'
import { applyDecorators, SetMetadata, ExecutionContext, createParamDecorator } from '@nestjs/common'

/** 开放接口 */
export function Public() {
  return SetMetadata(DecoratorEnum.PUBLIC_METADATA, true)
}

/** 指定当前接口不需要 Token 鉴权 */
export function AllowNoToken() {
  return SetMetadata(DecoratorEnum.ALLOW_NO_TOKEN, true)
}

/** 响应数据不包装直接返回 */
export function Raw() {
  return SetMetadata(DecoratorEnum.RAW_METADATA, true)
}

/** 既不需要鉴权也不需要包装数据 */
export function PublicRaw() {
  return applyDecorators(Public(), Raw())
}

/** 指定接口需要的权限组 */
export function RequirePermission(permissions: string[]) {
  return SetMetadata(DecoratorEnum.PERMISSION_METADATA, permissions)
}

/** 简化获取挂载在 Resuet 上的 Token 载荷的流程 */
export const TokenPayload = createParamDecorator(<K extends keyof JwtPayload>(field: K, context: ExecutionContext) => {
  const request = context.switchToHttp().getRequest<Request>()
  const payload = Reflect.get(request, AuthEnum.JWT_PAYLOAD) || {}
  return field ? payload[field] : payload
})
